// packageFT/travel-order-client/list/list.js
const app = getApp()
const orderType = ["", "wait_pay", "payed", "wait_comment", "refund"]
import { dateRange, timeDiff, formatTime } from '../../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    navList: ['全部订单', '待支付', '已支付', '待评价', '售后'],
    active: 0,
    orderPayId: null,
    total: 0,
    showKefu: false,
    guideShow: false,
    servicegGuide: {},
    currentOperationOrder: null,
    currentOperationBtn: null,
    complainShow: false,
    complainValue: '',
    complainImgs: [],
    loading: false
  },

  /**
   * 选项卡切换
   * @param {Object} e 
   */
  tabChange: function(e) {
    const { name } = e.detail
    this.setData({ active: name })
    this.getOrders()
  },

  /**
   * 获取订单列表
   */
  getOrders: function(callback) {
    const urlStr = app.getNetAddresss('plugin.guide.frontend.order.personal-need')
    const _this = this
    wx.showLoading({ title: '数据加载中...' })
    app._getNetWork({
      data: {
        tab: orderType[this.data.active]
      },
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const resList = resData.data.data
          const now = new Date()
          const nowStr = formatTime(now)
          console.log(nowStr,'-----------------nowStr')
          resList.forEach(item => {
            // 出行时间
            item.timeRange = dateRange(item.start_at, item.finish_at)
            // 支付倒计时
            if (item.pay_valid_time) {
              const countDownTime = timeDiff(nowStr, item.pay_valid_time, 'millisecond')
              // 倒计时时间戳
              item.countDownTime = countDownTime
            }
            // 确认订单提示
            if (item.status == 3) {
              const text = _this.timestampToDaysHoursMinutesSeconds(nowStr, item.accept_time)
              item.confirmOrderTips = text ? `提醒：行程已结束，系统将在${text}后自动为您确认行程结束。` : ''
            }
          })
          _this.setData({
            total: resData.data.total,
            list: resList
          })
        } else {
          app.tips(resData.msg || '数据加载失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
        callback && callback()
      }
    })
  },

  /**
   * 两个时间差的天/时/分
   * @param {String} start 开始时间
   * @param {String} end 结束时间
   * @returns {String} text 返回拼接后的字符串
   */
  timestampToDaysHoursMinutesSeconds: function(start, end) {
    const timestamp = timeDiff(start, end, 'millisecond')
    // 将时间戳从毫秒转换为秒
    const totalSeconds = timestamp / 1000;
    // 计算天数
    const days = Math.floor(totalSeconds / (60 * 60 * 24)); 
    // 计算小时（去掉天数的部分）
    const hours = Math.floor((totalSeconds % (60 * 60 * 24)) / (60 * 60)); 
    // 计算分钟（去掉天和小时的部分）
    const minutes = Math.floor((totalSeconds % (60 * 60)) / 60); 
    let text = ''
    if (days) {
      text += `${days}天`
      text += hours ? `${hours}小时` : ''
    } else if (hours) {
      text += `${hours}小时`
      text += minutes ? `${minutes}分钟` : ''
    } else if (minutes) {
      text += `${minutes}分钟`
    }
    return text
  },

  /**
   * 订单支付倒计时结束后更新订单信息
   * @param {Object} e 
   */
  countDownFinish: function(e) {
    const { order } = e.currentTarget.dataset
    const urlStr = app.getNetAddresss('plugin.guide.frontend.order.personal-need.detail')
    const data = { oid: order.order_id,  }
    const _this = this
    app._getNetWork({
      url: urlStr,
      data,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          // 出行时间
          let orderData = resData.data
          orderData.timeRange = dateRange(resData.data.start_at, resData.data.finish_at)
          let { list } = _this.data
          const orderIndex = list.findIndex(item => item.order_id == order.order_id)
          list.splice(orderIndex, 1, orderData)
          _this.setData({ list })
        }
      }
    })
  },

  /**
   * 订单按钮点击，根据按钮值判断用途
   * @param {Object} e 
   */
  operation: function(e) {
    const { btn, order, orderidx, disabled } = e.currentTarget.dataset
    // 为阻止按钮事件冒泡按钮绑定点击事件须用catchtap，catchtap无视diabled，故绑定到data-里处理
    if(disabled) return
    this.setData({
      currentOperationOrder: order,
      currentOperationBtn: btn
    })
    if (btn.value == 'pay') {
      const now = new Date()
      const nowStr = formatTime(now)
      const _timeDiff = timeDiff(nowStr, order.valid_time, 'millisecond')
      if (_timeDiff == 0) {
        app.tips('订单支付已超时！')
        return
      }
      // 订单支付，进入待支付页面
      wx.navigateTo({
        url: '/packageFT/travel-order-client/detail/detail?orderType=shop&order_id=' + order.order_id,
      });
    } else if (btn.value == 8) {
      // 联系导游-临时
      this.getGuide()
    } else if (btn.value == 'cancel-pay') {
      // 取消订单
      this._cancleOrder(order, btn)
    } else if (btn.value == 'customer-service') {
      // 联系客服
      this.getKefu()
    } else if(btn.value == 'need-order-surcharge-pay') {
      // 支付增值费
      const surcharge = encodeURIComponent(JSON.stringify(order.has_one_surcharge))
      wx.navigateTo({
        url: '/packageFT/travel-order-client/pay-added/pay-added?surcharge=' + surcharge,
      })
    } else if(btn.value == 'receive') {
      // 确认行程结束
      this.itineraryOver(order)
    } else if (btn.value == 'publish') {
      // 订单评论
      wx.navigateTo({
        url: `/packageFT/travel-order-client/feedback/feedback?oid=${order.order_id}&api=${btn.api}`,
      })
    } else if (btn.value == 'complain') {
      // 订单投诉
      this.setData({
        complainValue: '',
        complainShow: true
      })
    } else if (btn.value == 'refund') {
      // 申请售后
      wx.navigateTo({
        url: `/packageFT/travel-order-client/apply-customer-service/apply-customer-service?order_id=${order.order_id}&api=${btn.api}&active=${this.data.active}`,
      })
    }
  },

  /**
   * 关闭投诉弹窗
   */
  complainPopupClose: function() {
    if(this.data.loading) return
    this.setData({ complainShow: false })
  },

  /**
   * 图片选中上传(多图)
   * @param {Object} e 
   */
  afterRead: function(e) {
    const { file = [] } = e.detail
    let promiseArray = []
    const uploaderUrl = app.getNetAddresss(app.data.uploaderPicUrl)
    wx.showLoading({
      title: '上传中',
    })
    file.forEach(item => {
      promiseArray.push(new Promise((resolve, reject) => {
        wx.uploadFile({
          filePath: item.url,
          name: 'file',
          url: uploaderUrl,
          success: function(res) {
            resolve(res)
          },
          fail: function(err) {
            reject(err)
          }
        })
      }))
    })
    Promise.all(promiseArray).then(resArray => {
      wx.hideLoading()
      const addUrlArray = resArray.map(item => {
        const resData = JSON.parse(item.data)
        return {url: resData.data.img_url}
      })
      const currentImgUrls = [...this.data.complainImgs, ...addUrlArray]
      this.setData({ complainImgs: currentImgUrls })
    }).catch(err => {
      wx.hideLoading()
    })
  },

  /**
   * 删除已上传的图片
   * @param {Object} e 
   */
  deleteFile: function(e) {
    const { index } = e.detail
    const { field } = e.currentTarget.dataset
    let currentData = this.data.formData[field]
    const key = `formData.${field}`
    currentData.splice(index, 1)
    this.setData({
      [key]: currentData
    })
  },

  /**
   * 提交投诉
   */
  submitComplain: function() {
    const { complainValue, currentOperationOrder, currentOperationBtn, complainImgs } = this.data
    const { order_id } = currentOperationOrder
    if (!complainValue) {
      app.tips('请填写投诉内容！')
      return
    }
    if (!complainImgs.length) {
      app.tips('请上传图片凭证！')
      return
    }
    const images = complainImgs.map(item => {
      return item.url
    })
    const urlStr = app.getNetAddresss(currentOperationBtn.api)
    const data = {
      order_id,
      content: complainValue,
      images
    }
    const _this = this
    this.setData({ loading: true })
    app._postNetWork({
      url: urlStr,
      data,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          wx.showModal({
            title: '成功',
            content: '提交成功，平台人员将会为您处理该投诉！',
            showCancel: false,
            complete: (res) => {
              if (res.confirm) {
                _this.getOrders()
              }
            }
          })
          _this.setData({ complainShow: false })
        } else {
          app.tips(resData.msg || '提交失败！')
        }
      },
      complete: function() {
        _this.setData({ loading: false })
      }
    })
  },

  // 取消订单-确认提示
  _cancleOrder: function(item, btn) {
    const _this = this
    wx.showModal({
      title: '提示',
      content: '确定取消此订单?',
      complete: (res) => {
        if (res.confirm) {
          _this._sentRequest(btn.api, {oid: item.order_id})
        }
      }
    })
  },

  /**
   * 操作请求
   * @param {String} action 接口地址
   * @param {Object} params 参数
   */
  _sentRequest: function(action, params) {
    const urlStr = app.getNetAddresss(action)
    const _this = this
    wx.showLoading({ title: '加载中...' })
    app._getNetWork({
      url: urlStr,
      data: params,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.getOrders()
        } else {
          app.tips(resData.msg || '操作失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 申请客服
   * @param {Array} good 商品列表
   */
  getKefu() {
    const urlStr = app.getNetAddresss("goods.customer-service.index");
    wx.showLoading({ title: '加载中...' })
    app._postNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            customer_open:res.data.customer_open == 0?false:true,
            showKefu: true,
            cservice: res.data.cservice,
            service_QRcode: res.data.service_QRcode,
            service_mobile: res.data.service_mobile,
          });
        } else {
          app.tips(res.msg || '数据加载失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    });
  },

  /**
   * 联系导游
   */
  getGuide: function() {
    this.setData({ guideShow: true })
  },

  /**
   * 跳转到订单详情，判断待完善
   * @param {Object} e 
   */
  goDetail: function(e) {
    const { item } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/packageFT/travel-order-client/detail/detail?orderType=shop&order_id=' + item.order_id,
    })
  },

  /**
   * 确认行程结束
   * @param {Object} order 订单信息
   */
  itineraryOver: function(order) {
    wx.showModal({
      title: '提示',
      content: '确认行程结束吗？',
      complete: (res) => {
        if (res.confirm) {
          const _this = this
          const { order_id } = order
          if (!order_id) {
            app.tips('无订单信息！')
            return
          }
          const urlStr = app.getNetAddresss("plugin.guide.frontend.need-order-operate.confirm-receipt");
          wx.showLoading({ title: '加载中...' })
          app._postNetWork({
            url: urlStr,
            data: { oid: order_id },
            success: (resdata) => {
              var res = resdata.data;
              if (res.result == 1) {
                app.tips('订单已确认结束！')
                _this.getOrders()
              } else {
                app.tips(res.msg || '数据加载失败！')
              }
            },
            complete: function() {
              wx.hideLoading()
            }
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({ active: parseInt(options?.status || 0) })
    this.getOrders()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getOrders(() => wx.stopPullDownRefresh())
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})